<template>
  <div class="flex-row flex h-full">
    <!--  xl:min-w-login-right -->
    <div class="flex-1 flex h-full items-center justify-center relative overflow-hidden">
      <div class="flex-1 relative z-10">
        <h1 class="login-sys-title font-semibold"> 社区供应链管理系统 </h1>
        <div class="login bg-white px-4 py-12 xxs:px-9 xl:p-16">
          <h2 class="text-color-main text-center"> {{ t("aiot.login.userLogin") }} </h2>
          <a-form ref="formRef" :hide-required-mark="true" name="login" :model="formState" @finish="login">
            <a-form-item name="account" :rules="getRules(t('aiot.login.account'))">
              <a-input v-model:value="formState.account" autocomplete="on" :placeholder="t('aiot.login.account')" />
            </a-form-item>
            <a-form-item name="password" :rules="getRules(t('aiot.login.pwd'))" class="relative z-10">
              <a-input v-model:value="formState.password" type="password" :placeholder="t('aiot.login.pwd')" />
            </a-form-item>
            <!-- <a-form-item name="captcha" :rules="getRules('验证码')" class="relative z-10">
              <div class="flex flex-row items-center">
                <a-input v-model:value="formState.captcha" placeholder="请输入验证码" />
                <div class="pl-7">
                  <img :src="captchaUrl" style="height: 60px" @error="onCaptchaError" />
                </div>
              </div>
            </a-form-item> -->
            <a-form-item>
              <a-button type="primary" html-type="submit" block :loading="loading" :disabled="loginBtnDiabled">
                {{ loginBtnDiabled ? "登录成功，跳转中..." : t("aiot.login.login") }}
              </a-button>
              <a-typography-text v-show="errMsg" type="danger">
                {{ errMsg }}
              </a-typography-text>
            </a-form-item>
            <a-form-item name="rememberMe" class="!mb-0">
              <a-checkbox v-model:checked="formState.rememberMe">{{ t("aiot.login.remMe") }}</a-checkbox>
            </a-form-item>
          </a-form>
        </div>
        <div class="mt-16 text-center">
          <!-- <a href="https://beian.miit.gov.cn/" target="_blank">滇ICP备2024032898号-1</a> -->
          <a href="https://beian.miit.gov.cn/" target="_blank">滇ICP备2024033575号-1</a>
        </div>
      </div>
    </div>
  </div>
</template>
<script lang="ts" setup>
import { nextTick, onMounted, reactive, ref, watch } from "vue";
import { useI18n } from "vue-i18n";
import authCache from "/@/utils/cache/authCache";
import router, { MAIN_ROUTE_NAME, resetRouter } from "/@/router";
import { LoginUserInfo } from "/@/api/main/user/models";
import { getMeInfo, handleLogin } from "../api/main/user";

// const router = useRouter();
const { t } = useI18n();
const formRef = ref();
const loading = ref(false);
const errMsg = ref("");
const loginBtnDiabled = ref(false);
//captcha start
// const captchCheckStatus = ref(0);
// const captchaUrl = ref(DEFAULT_IMG_BASE64_STR);
// const isCaptchaLoading = ref(false);
// const onCaptchaLoad = () => {
//   isCaptchaLoading.value = false;
// };
// const clickCaptcha = async () => {
//   if (isCaptchaLoading.value) return;
//   isCaptchaLoading.value = true;
//   const re = await getCaptcha();
//   if (re) {
//     captchaUrl.value = re.captchaBase64s;
//   }
// };
// const onCaptchaError = () => {
//   captchaUrl.value = DEFAULT_IMG_BASE64_STR;
//   message.error(t("aiot.login.captchaLoadErr"));
// };
onMounted(() => {
  // clickCaptcha();
});
//captcha end
const formState = reactive({
  account: "",
  password: "",
  code: "",
  rememberMe: false,
  captcha: "",
});
watch(
  () => formState.account,
  () => {
    errMsg.value = "";
  }
);
watch(
  () => formState.password,
  () => {
    errMsg.value = "";
    isRemPass = false;
  }
);
watch(
  () => formState.code,
  () => {
    errMsg.value = "";
  }
);
function parseJwt(token) {
  var base64Url = token.split(".")[1];
  var base64 = base64Url.replace(/-/g, "+").replace(/_/g, "/");
  var jsonPayload = decodeURIComponent(
    atob(base64)
      .split("")
      .map(function (c) {
        return "%" + ("00" + c.charCodeAt(0).toString(16)).slice(-2);
      })
      .join("")
  );
  return JSON.parse(jsonPayload);
}
const login = async () => {
  // router.push({ name: MAIN_ROUTE_NAME });
  // if (formState.rememberMe) {
  //   authCache.setRemUserInfo({
  //     account: formState.account,
  //     password: formState.password,
  //   });
  // } else {
  //   authCache.setRemUserInfo(null);
  // }
  loading.value = true;
  errMsg.value = "";
  const re = await handleLogin({
    username: formState.account,
    password: formState.password,
  });

  let userInfo: Partial<LoginUserInfo> = {};
  if (re) {
    try {
      userInfo = parseJwt(re.access_token) as LoginUserInfo;
    } catch (ex) {
      console.warn("=======>parseJwt error", ex);
    }
    authCache.setToken(re.access_token);
    const meInfo = await getMeInfo({ useGlobalLoading: true });
    if (meInfo) {
      Object.assign(userInfo, meInfo);
    }
    authCache.setUserInfo(userInfo);
    loginBtnDiabled.value = true;
    resetRouter();
    router.push({ name: MAIN_ROUTE_NAME });
    if (formState.rememberMe) {
      authCache.setRemUserInfo({
        account: formState.account,
        password: formState.password,
      });
    } else {
      authCache.setRemUserInfo(null);
    }
  }
  loading.value = false;
};
//是否是从localStorage中获取到的md5密码缓存
let isRemPass = false;
onMounted(() => {
  const userInfo = authCache.getRemUserInfo();
  if (userInfo) {
    formState.rememberMe = true;
    Object.assign(formState, userInfo);
    //注意要nextTick 否则会触发watch 将isRemPass置为false
    nextTick(() => {
      isRemPass = true;
    });
  }
  loginBtnDiabled.value = false;
  // console.log("tag 2022-6-23 17:54");
});

function getRules(text) {
  return [{ required: true, message: "请输入" + text }];
}
</script>
<style lang="less">
.login-bg {
  min-width: 720px;
  min-height: 720px;
}
.login {
  max-width: 432px;
  border: 1px solid #ebedf0;
  box-shadow: 0 45px 30px 0 rgba(41, 72, 152, 0.03), 0 23px 15px 0 rgba(41, 72, 152, 0.03),
    0 9px 7px 0 rgba(41, 72, 152, 0.02), 0 2px 3px 0 rgba(41, 72, 152, 0.01);
  border-radius: 8px;
  h2 {
    font-size: 24px;
    line-height: 36px;
    margin-bottom: 48px;
  }
  margin: 0 auto;
}
@media (max-width: 452px) {
  .login {
    margin: 0 10px;
  }
}
.page-right {
  min-width: 663px;
}
.sys-title {
  font-size: 40px;
  line-height: 50px;
  margin-bottom: 32px;
  color: #e08344;
}
.login-sys-title {
  font-size: 30px;
  color: #e08344;
  text-align: center;
}
.sys-des {
  font-size: 36px;
  line-height: 36px;
  color: #e08344;
}
@media (max-width: 1400px) {
  .sys-title {
    font-size: 36px;
    line-height: 46px;
    margin-bottom: 28px;
  }
  .sys-des {
    font-size: 34px;
    line-height: 32px;
  }
}
</style>
